@page "/CreateTicket"
@using System.Data
@using System.ComponentModel.DataAnnotations
@using AdminSecurity.Extensions
@using Identity.Models
@using WorkOrder.Interfaces
@using WorkOrder.Models
@using WorkSystem.Data
@using Microsoft.AspNetCore.Components.Rendering
@attribute [UserNavigation("新建工单")]
@attribute [TabItemOption(Text = "新建工单", Icon = "fa-solid fa-file-circle-plus")]

@rendermode InteractiveServer

<PageTitle>新建工单</PageTitle>

 
    <div class="container mt-4">
        <div class="row mb-4">
            <div class="col-md-12">
                <h3 class="text-primary">新建工单</h3>
                <p class="text-muted">请选择一个模板并填写相关信息以创建新的工单。</p>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-12">
                <Select @bind-Value="模板ID" ShowSearch="true" Items="@TemplateList" OnSelectedItemChanged="OnTemplateChanged" PlaceHolder="请选择工单模板">
                  
                </Select>
    
                            <div class="mt-3">
                            <h5 class="text-info">模板字段:</h5>
                            <ul class="list-group"> 
                                @if (TemplateFields != null && TemplateFields.Any())
                                {
                                    @foreach (var field in TemplateFields)
                                    {
                                        <li class="list-group-item">@field.字段名称</li>
                                    }
                                }
                                else
                                {
                                    <li class="list-group-item text-warning">暂无字段信息</li>
                                }
                            </ul>
                            </div>
                
            </div>
        </div>
        <div class="row mb-4"> 
            <div class="col-md-12">
                <Select @bind-Value="流程ID" ShowSearch="true" Items="@ProcessList" PlaceHolder="请选择流程模板">
                    <ItemTemplate>
                        @if (string.IsNullOrEmpty(context.Value))
                        {
                            <div class="mt-3 text-danger">请选择一个流程模板</div>
                        }
                        else
                        {
                            <div class="mt-3 text-success">已选择流程模板: @context.Text</div>
                        }
                    </ItemTemplate>
                </Select>
            </div>
        </div>
        @if (!string.IsNullOrEmpty(模板ID))
        {
            <div class="row">
                <div class="col-md-12">
                    <Table TItem="DynamicObject" DynamicContext="DataTableDynamicContext" 
                           IsBordered="true" IsMultipleSelect="true" ModelEqualityComparer="ModelEqualityComparer"  
                           ShowToolbar="true" ShowExtendButtons="true" ShowSkeleton="true" IsExcel="true">
                        <TableToolbarTemplate>
                            <TableToolbarButton TItem="DynamicObject" Color="Color.Info" Icon="fa-solid fa-user" Text="提交工单" OnClickCallback="@ShowAccountDetails" />
                        </TableToolbarTemplate>
                    </Table>
                </div>
            </div>
        }
        else
        {
            <div class="row mt-3">
                <div class="col-md-12 text-center">
                    <div class="alert alert-warning" role="alert">
                        请选择一个模板以加载表单
                    </div>
                </div>
            </div>
        }
    </div>
 
@code {    
    private string 流程ID { get; set; } = string.Empty;
    private string  模板ID { get; set; } = string.Empty;
    private List<SelectedItem> TemplateList { get; set; } = new();
    private List<模板字段表> TemplateFields { get; set; } = new();
    private DataTable UserData { get; } = new DataTable();
    private DataTableDynamicContext? DataTableDynamicContext { get; set; }
    
    [Inject]
    [NotNull]
    private ISystemNotificationService SystemNotificationService { get; set; }
    private List<SelectedItem> ProcessList { get; set; } = new();
    [Inject]
    [NotNull]
    private  MyIdentityContext AppContext {get;set;}
 
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }
 
    [Inject]
    private IWorkOrderService WorkOrderService { get; set; }
 
    [Inject]
    private ToastService ToastService { get; set; }
    private async Task OnTemplateChanged(SelectedItem item)
    {
         
            try
            {
                if (string.IsNullOrEmpty(item.Value))
                {
                    // 清空模板字段
                    TemplateFields.Clear();

                    // 清空并重置 DataTable 和 DynamicContext
                    InitDataTable();
                    DataTableDynamicContext = new DataTableDynamicContext(UserData, null);

                    await ToastService.Warning("未选择模板", "动态表格已清空");
                    return;
                }

                // 根据选择的模板 ID 加载模板字段
                TemplateFields = await WorkOrderService.GetTemplates(item.Value);

                // 重新初始化 DataTable 和 DynamicContext
                InitDataTable();
                CreateContext();
                StateHasChanged();
                await ToastService.Success("模板加载成功", "表格已根据新模板更新");
            }
            catch (Exception ex)
            {
                await ToastService.Error("模板加载失败", ex.Message);
            }
    }
    protected override async Task OnInitializedAsync()
    {
        // 从后端 API 获取模板字段
        TemplateList = (await WorkOrderService.GetTemplateList())
            .Select(i => new SelectedItem { Value = i.模板ID!, Text = i.模板名称 })
            .ToList();

        // 添加一个 "请选择" 的空值选项
        TemplateList.Insert(0, new SelectedItem { Value = string.Empty, Text = "请选择" });

        ProcessList = (await WorkOrderService.GetProcessList())
            .Select(p => new SelectedItem { Value = p.流程ID!, Text = p.流程名称 })
            .ToList();

        
    }

    private async Task ShowAccountDetails(IEnumerable<DynamicObject> items)
    {
        try
        {
            if (!items.Any())
            {
                await ToastService.Error("加载失败", "您还未选择任何工单数据");
                return;
            }

            // 检查必填字段是否填写
            foreach (var item in items)
            {
                foreach (var field in TemplateFields.Where(f => f.是否必填))
                {
                    var value = item.GetValue(field.字段名称);
                    if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                    {
                        await ToastService.Error("加载失败", $"必填字段 '{field.字段名称}' 未填写");
                        return;
                    }
                }
            }

            // 获取选中的工单数据
            var selectedData = items.Select(item =>
            {
                var data = new Dictionary<string, object?>();
                foreach (var field in TemplateFields)
                {
                    var value = item.GetValue(field.字段名称);
                    data[field.字段名称] = value; // 使用字段名称作为键
                }
                return data;
            }).ToList();

            // 构建对话框内容
            var dialogContent = new RenderFragment(builder =>
            {
                int seq = 0;
                builder.OpenElement(seq++, "div");
                builder.AddAttribute(seq++, "class", "dialog-content p-3");
                
                foreach (var data in selectedData)
                {
                    builder.OpenElement(seq++, "div");
                    builder.AddAttribute(seq++, "class", "data-group mb-4 border rounded p-3");
                    builder.AddAttribute(seq++, "style", "background-color: #f9f9f9;"); // 添加背景颜色

                    builder.OpenElement(seq++, "h5");
                    builder.AddAttribute(seq++, "class", "group-title text-danger mb-3"); // 修改标题颜色为鲜艳的红色
                    builder.AddContent(seq++, "工单详情");
                    builder.CloseElement();

                    foreach (var kv in data)
                    {
                        var displayName = TemplateFields.FirstOrDefault(f => f.字段名称 == kv.Key)?.字段名称 ?? kv.Key;

                        builder.OpenElement(seq++, "div");
                        builder.AddAttribute(seq++, "class", "data-field d-flex justify-content-between align-items-center mb-2");

                        builder.OpenElement(seq++, "span");
                        builder.AddAttribute(seq++, "class", "field-label font-weight-bold text-danger"); // 修改标签颜色为鲜艳的红色
                        builder.AddContent(seq++, $"{displayName}:");
                        builder.CloseElement();

                        builder.OpenElement(seq++, "span");
                        builder.AddAttribute(seq++, "class", "field-value text-warning"); // 修改值颜色为鲜艳的黄色
                        builder.AddContent(seq++, $"{kv.Value}");
                        builder.CloseElement();

                        builder.CloseElement();
                    }

                    builder.CloseElement();
                }

                builder.CloseElement();
            });

            var option = new DialogOption()
            {
                Title = "新建订单详情",
                Size = Size.ExtraLarge, // 调整对话框尺寸
                BodyTemplate = dialogContent,
                ShowSaveButton = true,
                SaveButtonText = "提交工单",
                OnSaveAsync = async () =>
                {
                    try
                    {   
                        var title = "批量创建的工单";
                        var description = $"用户{AppContext.UserName} 批量创建的工单";
                        // 将选中的工单数据保存到后端
                        var createdWorkOrders = await WorkOrderService.BatchCreateWorkOrdersAsync(模板ID, selectedData, title, description, AppContext.UserName,流程ID);
                        var saveResult = createdWorkOrders.Count == selectedData.Count;
                        if (saveResult)
                        {  
                            await ToastService.Success("保存成功", "工单已成功保存");
                             
                            foreach (var item in createdWorkOrders)
                            {
                         var permissionInfo = await WorkOrderService.GetProcessInstanceByWorkOrderIdAsync(item.工单id);

                                if (permissionInfo?.当前节点 != null)
                            {
                                switch (permissionInfo.当前节点.负责人规则类型)
                                {
                                    case AssignRuleType.角色:
                                        if (!string.IsNullOrEmpty(permissionInfo.当前节点.负责人规则参数))
                                        {
                                            await SystemNotificationService.SendSystemNotificationAsync(
                                                Constant.RoleMessagge,
                                                DispatchType.Toast,
                                                "您有新的工单等待处理",
                                                $"用户:{AppContext.UserName} 创建了工单等待您审核 1 个工单",
                                                permissionInfo.当前节点.负责人规则参数
                                            );
                                        }
                                        break;

                                    case AssignRuleType.指定用户:
                                        if (!string.IsNullOrEmpty(permissionInfo.当前节点.负责人规则参数))
                                        {
                                            await SystemNotificationService.SendSystemNotificationAsync(
                                                Constant.UserMessagge,
                                                DispatchType.Toast,
                                                "您有新的工单等待处理",
                                                $"用户:{AppContext.UserName} 创建了工单等待您审核 1 个工单",
                                                permissionInfo.当前节点.负责人规则参数
                                            );
                                        }
                                        break;
                                }
                            }
                            }
                            InitDataTable();
                            CreateContext();
                            StateHasChanged();
                            return await Task.FromResult(true) ; // 关闭对话框
                        }
                        else
                        {
                            await ToastService.Error("保存失败", "工单保存失败，请重试");
                            return await Task.FromResult(false) ;
                        }
                    }
                    catch (Exception ex)
                    {
                        await ToastService.Error("保存失败", ex.Message);
                        return await Task.FromResult(false) ;
                    }
                }
            };

            await DialogService.Show(option);
        }
        catch (Exception ex)
        {
            // 处理异常，例如显示错误提示
            await ToastService.Error("加载失败", ex.Message);
        }
    }
    private void InitDataTable()
    {
        // 清空 DataTable
        UserData.Clear();

        // 移除主键列设置
        UserData.Reset();

        // 添加主键列
        var primaryKeyColumn = new DataColumn("Id", typeof(Guid))
        {
            Unique = true,
            AllowDBNull = false,
            DefaultValue = Guid.NewGuid()
        };
        UserData.Columns.Add(primaryKeyColumn);
        UserData.PrimaryKey = new[] { primaryKeyColumn };

        // 根据模板字段动态生成 DataTable 列
        foreach (var field in TemplateFields)
        {
            var columnType = field.数据类型 switch
            {
                "number" => typeof(decimal),
                "datetime" => typeof(DateTime),
                "boolean" => typeof(bool),
                _ => typeof(string)
            };

            UserData.Columns.Add(field.字段名称, columnType);
        }
    }

    private static bool ModelEqualityComparer(IDynamicObject x, IDynamicObject y) =>
        x.GetValue("Id")?.ToString() == y.GetValue("Id")?.ToString();

    private void CreateContext()
    {
        DataTableDynamicContext = new DataTableDynamicContext(UserData, (context, col) =>
        {
            var field = TemplateFields.FirstOrDefault(f => f.字段名称 == col.GetFieldName());
            if (field != null)
            {
                if (field.是否必填)
                {
                    context.AddRequiredAttribute(field.字段名称, $"{field.字段名称} 是必填项");
                }

                context.AddAutoGenerateColumnAttribute(field.字段名称, new KeyValuePair<string, object?>[]
                {
                    new(nameof(AutoGenerateColumnAttribute.Text), field.字段名称)
                });
            }
        })
        {
            OnDeleteAsync = items =>
            {
                foreach (var item in items)
                {
                    var id = item.GetValue("Id");
                    if (id != null)
                    {
                        var row = UserData.Rows.Find(id);
                        if (row != null)
                        {
                            UserData.Rows.Remove(row);
                        }
                    }
                }

                UserData.AcceptChanges();
                return Task.FromResult(true);
            },
            OnChanged = args =>
            {
                if (args.ChangedType == DynamicItemChangedType.Add)
                {
                    var item = args.Items.First();
                    item.SetValue("Id", Guid.NewGuid());
                    foreach (var field in TemplateFields)
                    {
                        
                        if (field.数据类型 == "datetime")
                        {
                            item.SetValue(field.字段名称, DateTime.Now);
                        }
                        else if (field.数据类型 == "number")
                        {
                            item.SetValue(field.字段名称, 0m);
                        }
                        else if (field.数据类型 == "boolean")
                        {
                            item.SetValue(field.字段名称, false);
                        }
                        else
                        {
                            item.SetValue(field.字段名称, string.Empty);
                        }
                    }
                }

                return Task.CompletedTask;
            }
        };
    }
 

    
}